<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据统计</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-50">
    <div class="max-w-md mx-auto h-screen flex flex-col">
        <!-- 顶部导航 -->
        <header class="bg-white shadow-sm">
            <div class="px-4 py-6">
                <h1 class="text-xl font-semibold">数据统计</h1>
                <!-- 时间范围选择 -->
                <div class="flex gap-2 mt-4 overflow-x-auto">
                    <button onclick="changeTimeRange('week')" class="px-4 py-1 bg-blue-100 text-blue-600 rounded-full text-sm whitespace-nowrap">
                        本周
                    </button>
                    <button onclick="changeTimeRange('month')" class="px-4 py-1 bg-gray-100 text-gray-600 rounded-full text-sm whitespace-nowrap">
                        本月
                    </button>
                    <button onclick="changeTimeRange('all')" class="px-4 py-1 bg-gray-100 text-gray-600 rounded-full text-sm whitespace-nowrap">
                        全部
                    </button>
                </div>
            </div>
        </header>

        <!-- 统计内容 -->
        <div class="flex-1 overflow-y-auto">
            <div class="p-4 space-y-6">
                <!-- 总览卡片 -->
                <div class="grid grid-cols-2 gap-4">
                    <div class="bg-white rounded-xl p-4 shadow-sm">
                        <div class="text-sm text-gray-500">总盈利</div>
                        <div id="totalProfit" class="text-2xl font-semibold text-green-500 mt-1">+0</div>
                    </div>
                    <div class="bg-white rounded-xl p-4 shadow-sm">
                        <div class="text-sm text-gray-500">胜率</div>
                        <div id="winRate" class="text-2xl font-semibold mt-1">0%</div>
                    </div>
                </div>

                <!-- 盈利趋势图 -->
                <div class="bg-white rounded-xl p-4 shadow-sm">
                    <h3 class="text-lg font-medium mb-4">盈利趋势</h3>
                    <canvas id="profitChart" height="200"></canvas>
                </div>

                <!-- 战队表现 -->
                <div class="bg-white rounded-xl p-4 shadow-sm">
                    <h3 class="text-lg font-medium mb-4">战队表现</h3>
                    <div id="teamPerformance" class="space-y-4">
                        <!-- 战队表现将通过JavaScript动态添加 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部导航 -->
        <nav class="bg-white border-t border-gray-200">
            <div class="flex justify-around py-3">
                <a href="home.html" class="flex flex-col items-center text-gray-400">
                    <i class="fas fa-list-ul"></i>
                    <span class="text-xs mt-1">记录</span>
                </a>
                <a href="zhandui.html" class="flex flex-col items-center text-gray-400">
                    <i class="fas fa-users"></i>
                    <span class="text-xs mt-1">战队</span>
                </a>
                <a href="stats.html" class="flex flex-col items-center text-blue-500">
                    <i class="fas fa-chart-bar"></i>
                    <span class="text-xs mt-1">统计</span>
                </a>
            </div>
        </nav>
    </div>

    <script>
        // API基础URL
        const API_BASE_URL = window.location.origin + '/api';
        let profitChart;
        let currentTimeRange = 'week'; // 默认时间范围

        // 加载统计数据
        async function loadStats(timeRange = 'week') {
            try {
                currentTimeRange = timeRange;
                const response = await fetch(`${API_BASE_URL}/matches/stats?timeRange=${timeRange}`);
                const stats = await response.json();
                
                // 更新总览数据
                const totalProfitElement = document.getElementById('totalProfit');
                totalProfitElement.textContent = (stats.total_profit > 0 ? '+' : '') + stats.total_profit;
                totalProfitElement.classList.remove('text-green-500', 'text-red-500');
                totalProfitElement.classList.add(stats.total_profit >= 0 ? 'text-green-500' : 'text-red-500');
                
                document.getElementById('winRate').textContent = stats.win_rate + '%';
                
                // 更新盈利趋势图
                updateProfitChart(stats.weekly_profits, timeRange);
                
                // 更新战队表现
                updateTeamPerformance(stats.team_performance);
            } catch (error) {
                console.error('Error loading stats:', error);
            }
        }

        // 更新盈利趋势图
        function updateProfitChart(data, timeRange) {
            const ctx = document.getElementById('profitChart').getContext('2d');
            
            // 根据时间范围设置不同的标签
            let labels = [];
            if (timeRange === 'week') {
                labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            } else if (timeRange === 'month') {
                // 如果是月视图，标签为第几周
                labels = data.map((_, index) => `第${index + 1}周`);
            } else {
                // 如果是全部视图，使用最近7天的日期
                const today = new Date();
                labels = Array(7).fill().map((_, i) => {
                    const date = new Date(today);
                    date.setDate(date.getDate() - 6 + i);
                    return `${date.getMonth() + 1}/${date.getDate()}`;
                });
            }
            
            if (profitChart) {
                profitChart.destroy();
            }
            
            profitChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '盈利',
                        data: data,
                        borderColor: 'rgb(59, 130, 246)',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.1,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let value = context.raw;
                                    return value > 0 ? `盈利: +${value}` : `亏损: ${value}`;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    }
                }
            });
        }

        // 更新战队表现
        function updateTeamPerformance(teamsData) {
            const teamPerformance = document.getElementById('teamPerformance');
            
            if (!teamsData || teamsData.length === 0) {
                teamPerformance.innerHTML = '<div class="text-center text-gray-500 py-4">暂无数据</div>';
                return;
            }
            
            teamPerformance.innerHTML = teamsData.map(team => `
                <div class="mb-4">
                    <div class="flex justify-between mb-1">
                        <span class="font-medium">${team.name}</span>
                        <span class="text-sm ${team.profit >= 0 ? 'text-green-500' : 'text-red-500'}">
                            ${team.profit >= 0 ? '+' : ''}${team.profit}
                        </span>
                    </div>
                    <div class="flex justify-between mb-1 text-sm text-gray-500">
                        <span>${team.league}</span>
                        <span>胜率 ${team.win_rate}%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2.5">
                        <div class="bg-blue-500 h-2.5 rounded-full" style="width: ${team.win_rate}%"></div>
                    </div>
                </div>
            `).join('');
        }

        // 切换时间范围
        function changeTimeRange(range) {
            if (range === currentTimeRange) return; // 避免重复加载
            
            // 更新按钮样式
            document.querySelectorAll('.flex.gap-2.mt-4 button').forEach(button => {
                const buttonText = button.textContent.trim();
                const isActive = (range === 'week' && buttonText === '本周') ||
                                (range === 'month' && buttonText === '本月') ||
                                (range === 'all' && buttonText === '全部');
                
                if (isActive) {
                    button.className = 'px-4 py-1 bg-blue-100 text-blue-600 rounded-full text-sm whitespace-nowrap';
                } else {
                    button.className = 'px-4 py-1 bg-gray-100 text-gray-600 rounded-full text-sm whitespace-nowrap';
                }
            });
            
            // 加载新数据
            loadStats(range);
        }

        // 初始加载
        loadStats('week');
    </script>
</body>
</html> 